from PyQt5.QtWidgets import (QMainWindow, QWidget, QGridLayout,
                           QPushButton, QVBoxLayout, QHBoxLayout, QLabel,
                           QMessageBox, QMenuBar, QMenu, QAction, QActionGroup)
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QFont, QIcon
from game_logic import GameLogic, Difficulty

class MinesweeperCell(QPushButton):
    def __init__(self, x: int, y: int):
        super().__init__()
        self.x = x
        self.y = y
        self.setFixedSize(40, 40)
        self.setFont(QFont('Arial', 14))
        self.setStyleSheet('''
            QPushButton {
                background-color: #e0e0e0;
                border: 2px solid #808080;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: #d0d0d0;
            }
        ''')

class MinesweeperUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.game = GameLogic()
        self.time_count = 0
        self.setup_ui()

    def setup_ui(self):
        """设置游戏界面"""
        self.setWindowTitle('扫雷游戏')
        
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建主窗口部件
        self.central_widget = QWidget()
        self.setCentralWidget(self.central_widget)
        self.main_layout = QVBoxLayout(self.central_widget)
        
        # 创建状态栏
        self.create_status_bar()
        
        # 创建游戏网格
        self.create_grid()
        
        # 初始化定时器
        self.timer = QTimer()
        self.timer.timeout.connect(self.update_timer)
        
        self.setStyleSheet('''
            QMainWindow {
                background-color: #f0f0f0;
            }
        ''')
        
        self.resize(400, 500)
        self.center_window()

    def center_window(self):
        """将窗口居中显示"""
        frame_geometry = self.frameGeometry()
        screen_center = self.screen().availableGeometry().center()
        frame_geometry.moveCenter(screen_center)
        self.move(frame_geometry.topLeft())

    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        game_menu = menubar.addMenu('选项')
        
        # 创建新游戏动作
        new_game_action = QAction('新游戏', self)
        new_game_action.triggered.connect(self.restart_game)
        game_menu.addAction(new_game_action)
        
        # 添加分隔线
        game_menu.addSeparator()
        
        # 创建难度选择菜单
        difficulty_menu = QMenu('难度', self)
        difficulty_group = QActionGroup(self)
        
        # 创建难度选项
        difficulties = {
            Difficulty.BEGINNER: '初级',
            Difficulty.INTERMEDIATE: '中级',
            Difficulty.EXPERT: '高级'
        }
        
        for difficulty, name in difficulties.items():
            action = QAction(name, self, checkable=True)
            action.setData(difficulty)
            difficulty_group.addAction(action)
            if difficulty == self.game.current_difficulty:
                action.setChecked(True)
            action.triggered.connect(self.change_difficulty)
            difficulty_menu.addAction(action)
        
        game_menu.addMenu(difficulty_menu)

    def change_difficulty(self):
        """更改游戏难度"""
        action = self.sender()
        if action and action.isChecked():
            difficulty = action.data()
            self.game.set_difficulty(difficulty)
            self.resize_window_for_difficulty()
            self.restart_game()

    def resize_window_for_difficulty(self):
        """根据难度调整窗口大小"""
        cell_size = 40
        padding = 60  # 为菜单栏和状态栏预留空间
        width = self.game.cols * cell_size
        height = self.game.rows * cell_size + padding
        self.resize(width, height)
        self.center_window()

    def create_status_bar(self):
        """创建状态栏"""
        status_layout = QHBoxLayout()
        
        # 剩余地雷计数器
        self.flag_label = QLabel(f'地雷: {self.game.flags_left}')
        self.flag_label.setStyleSheet('font-size: 16px; color: #d63031;')
        
        # 计时器
        self.timer_label = QLabel('时间: 0')
        self.timer_label.setStyleSheet('font-size: 16px; color: #00b894;')
        
        status_layout.addWidget(self.flag_label)
        status_layout.addStretch()
        status_layout.addWidget(self.timer_label)
        
        self.main_layout.addLayout(status_layout)

    def create_grid(self):
        """创建游戏网格"""
        self.grid = QGridLayout()
        self.grid.setSpacing(2)
        self.cells = []
        
        for row in range(self.game.rows):
            row_cells = []
            for col in range(self.game.cols):
                cell = MinesweeperCell(row, col)
                cell.clicked.connect(lambda checked, x=row, y=col: self.handle_click(x, y))
                cell.setContextMenuPolicy(Qt.CustomContextMenu)
                cell.customContextMenuRequested.connect(
                    lambda pos, x=row, y=col: self.handle_right_click(x, y))
                self.grid.addWidget(cell, row, col)
                row_cells.append(cell)
            self.cells.append(row_cells)
        
        self.main_layout.addLayout(self.grid)

    def handle_click(self, x: int, y: int):
        """处理左键点击事件"""
        if self.game.game_over:
            return
            
        if self.game.grid[x][y].is_flagged:
            return
            
        if self.game.first_click:
            self.game.first_click = False
            self.game.place_mines(x, y)
            self.timer.start(1000)
            
        if self.game.grid[x][y].is_mine:
            self.game.game_over = True
            self.show_all_mines()
            QMessageBox.information(self, '游戏结束', '很遗憾，你踩到了地雷！')
            self.timer.stop()
        else:
            revealed_cells = self.game.reveal_cell(x, y)
            self.update_revealed_cells(revealed_cells)
            if self.game.check_win():
                self.game.game_over = True
                QMessageBox.information(self, '恭喜', '你赢了！')
                self.timer.stop()

    def handle_right_click(self, x: int, y: int):
        """处理右键点击事件"""
        if self.game.game_over or self.game.first_click:
            return
            
        if self.game.toggle_flag(x, y):
            cell = self.cells[x][y]
            if self.game.grid[x][y].is_flagged:
                cell.setText('🚩')
            else:
                cell.setText('')
            self.flag_label.setText(f'地雷: {self.game.flags_left}')

    def update_revealed_cells(self, revealed_cells):
        """更新已揭示的格子"""
        colors = ['blue', 'green', 'red', 'purple', 'maroon', 'turquoise', 'black', 'gray']
        for x, y, num_mines in revealed_cells:
            cell = self.cells[x][y]
            if num_mines > 0:
                cell.setText(str(num_mines))
                cell.setStyleSheet(f'''
                    QPushButton {{
                        color: {colors[num_mines - 1]};
                        background-color: #ffffff;
                        border: 1px solid #808080;
                        border-radius: 5px;
                    }}
                ''')
            else:
                cell.setStyleSheet('''
                    QPushButton {
                        background-color: #ffffff;
                        border: 1px solid #808080;
                        border-radius: 5px;
                    }
                ''')

    def show_all_mines(self):
        """显示所有地雷"""
        mines = self.game.get_all_mines()
        for x, y in mines:
            cell = self.cells[x][y]
            cell.setText('💣')
            cell.setStyleSheet('''
                QPushButton {
                    background-color: #ff0000;
                    border: 1px solid #808080;
                    border-radius: 5px;
                }
            ''')

    def update_timer(self):
        """更新计时器"""
        self.time_count += 1
        self.timer_label.setText(f'时间: {self.time_count}')

    def restart_game(self):
        """重新开始游戏"""
        self.game.initialize_grid()
        self.time_count = 0
        self.timer.stop()
        self.timer_label.setText('时间: 0')
        self.flag_label.setText(f'地雷: {self.game.flags_left}')
        
        # 清除旧的网格布局
        for i in reversed(range(self.grid.count())): 
            self.grid.itemAt(i).widget().setParent(None)
        
        # 重新创建游戏网格
        self.create_grid()
        
        for row in self.cells:
            for cell in row:
                cell.setText('')
                cell.setStyleSheet('''
                    QPushButton {
                        background-color: #e0e0e0;
                        border: 2px solid #808080;
                        border-radius: 5px;
                    }
                    QPushButton:hover {
                        background-color: #d0d0d0;
                    }
                ''') 